import React from 'react'
import "./style.less"
import { useHistory } from "react-router-dom"
import { useDispatch, useSelector } from "react-redux"
import { addCollection, delCollection } from "../../../redux/actions/collect"
import classnames from "classnames"


export default function StoreAndBuyView ({ id }) {

  const history = useHistory();
  const dispatch = useDispatch();
  const collects = useSelector(state => state.collect)
  const user = useSelector(state => state.auth.user)
  // 本地存储读数据：
  const username = localStorage.getItem("username");
  console.log(collects);

  function clickHandle () {
    if (!username) {
      history.push("/login")
    } else {
      if (!isStore()) {
        dispatch(addCollection(id))
      } else {
        dispatch(delCollection(id))
      }
    }
  }


  // ***************判断id是否存在：存在删除，不存在添加************
  function isStore () {
    return collects.some((ele) => {
      return ele === id
    })
  }

  return (
    <div className="buy-and-store">
      <div className="buy-store-container clear-fix">
        <div className="item-container float-left">
          <span
            className={classnames('selected', { "o": isStore() })}
            onClick={clickHandle}
          >{isStore() ? "取消收藏" : "收藏"}</span>
        </div>
        <div className="item-container float-left">
          <span className="selected">购买</span>
        </div>
      </div>
    </div>

  )
}
